package lu.med.praxiswahl.wahlumed.dao.beans;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import lu.med.praxiswahl.wahlumed.dao.beans.daointerface.PhysicianLetterDAOInt;
import lu.med.praxiswahl.wahlumed.model.beans.CustomerTBL;
import lu.med.praxiswahl.wahlumed.model.beans.PhysicianLetterTBL;

/**
 * Session Bean implementation class PhysicianLetterDAO
 */
@Stateless(mappedName = "LetterDao")
public class PhysicianLetterDAO implements PhysicianLetterDAOInt {

	@PersistenceContext(unitName = "gynaekomedic-ejbPU")
	private EntityManager em;

	/**
	 * Default constructor.
	 */
	public PhysicianLetterDAO() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void persist(PhysicianLetterTBL entry) {
		em.persist(entry);
		em.flush();

	}

	@Override
	public void delete(Long id) {

		// PhysicianLetterTBL letter = em.find(PhysicianLetterTBL.class, id);

		PhysicianLetterTBL letter = (PhysicianLetterTBL) em.createQuery(
				"select p from PhysicianLetterTBL p where p.id = '" + id + "'")
				.getSingleResult();

		CustomerTBL cust = letter.getCustomer();

		cust.getDocLetter().remove(letter);

		em.remove(letter);
		em.flush();

	}

	@Override
	public void update(PhysicianLetterTBL todo) {

		em.merge(todo);
		em.flush();

	}

	@Override
	public List<PhysicianLetterTBL> findLetterByCustomer(String matricule) {
		try {

			@SuppressWarnings("unchecked")
			List<PhysicianLetterTBL> resultList = (List<PhysicianLetterTBL>) em
					.createQuery(
							"select p from PhysicianLetterTBL p where p.customer = '"
									+ matricule + "' order by p.datum desc")
					.getResultList();
			return resultList;
		} catch (Exception e) {
			throw new RuntimeException(
					"letter  for this customer can't be found ", e);
		}
	}

}
